package com.cicadamob.contact.api.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.os.RemoteException;
import android.telephony.PhoneNumberUtils;
import android.text.TextUtils;

import com.cicadamob.contact.api.Utils.StringUtil;
import com.cicadamob.contact.api.Utils.Data.SharedPreferencesUtil;
import com.cicadamob.contact.api.Utils.pinyin.PinyinTools;
import com.cicadamob.contact.api.service.AppDbHelper.APP_CONTACTS;
import com.cicadamob.contact.api.service.AppDbHelper.APP_CONTACTS_DATA;
import com.gmccgz.im.sdk.http.bean.UserCard;

/**
 * 操作联系人数据库类<br>
 * 联系人有两个数据库表APP_CONTACTS/APP_CONTACTS_DATA<br>
 * <br>
 * 限制：<br>
 * 同一个联系人可以设置多个号码<br>
 * 同一个号码只能给一个联系人（不允许不同联系人有相同号码）<br>
 * 姓名不能为空<br>
 * 姓名不能重复（相同姓名看成同一联系人）<br>
 * 
 * @author xmq
 *
 */
public class APPContactDao {

	/**
	 * 联系人数据库发生改变时，发生广播
	 */
	public static final String APP_CONTACT_CHNAGE = "com.robin.phone.contact.action.contact_change";

	/**
	 * 联系人数据库发生改变时，发生广播可能携带的参数<br>
	 * 修改联系人操作类型，可能值有（add,update,reomve,bachadd）
	 */
	public static final String APP_CONTACT_CHNAGE_TYPE = "contact_change_type";
	/**
	 * 联系人数据库发生改变时，发生广播可能携带的参数<br>
	 * 修改联系人的id
	 */
	public static final String APP_CONTACT_CHNAGE_ID = "contact_id";

	/**
	 * APP_CONTACT_CHNAGE_TYPE 的值
	 */
	public static final String APP_CONTACT_CHNAGE_TYPE_ADD = "add";
	public static final String APP_CONTACT_CHNAGE_TYPE_UPDATE = "update";
	public static final String APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON = "update_common";
	public static final String APP_CONTACT_CHNAGE_TYPE_REMOVE = "reomve";
	public static final String APP_CONTACT_CHNAGE_TYPE_REMOVE_All = "reomve_all";
	public static final String APP_CONTACT_CHNAGE_TYPE_BACHADD = "bachadd";

	/**
	 * 获取所有联系人(安装状态，排序，首字母，全拼，名称，电话号码，id) 联系人多个号码情况下，只返回第一个号码
	 * 
	 * @param mContext
	 * @return
	 */
	public static ArrayList<Contact> getAllContacts(Context mContext) {
		Map<String, String> phones = getInstallPhone(mContext);

		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join  "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME + ",cd." + APP_CONTACTS_DATA.ID, null);

		ArrayList<Contact> contacts = new ArrayList<Contact>();
		long lasteContactId = -1;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));

			Contact item = new Contact();
			if (lasteContactId == contact_id)
				continue;
			else
				lasteContactId = contact_id;
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			// 安装状态
			for (String p : phones.keySet()) {
				if (phoneNumber.equals(p)) {
					item.setInstall(1);
					break;
				}
			}
			// TODO 有问题？
			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;

			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setCommonContact(isCommon == 0 ? false : true);

			if (StringUtil.isEmpty(displayName)) {
				item.setLetter("#");
			} else {
				displayName = displayName.trim();
				String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
				char[] firstChar = letter.toCharArray();
				if (firstChar != null && firstChar.length > 0) {
					if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
						item.setLetter(letter.toUpperCase());
					} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
						item.setLetter(letter);
					} else {
						item.setLetter("#");
					}
				} else {
					item.setLetter("#");
				}
			}
			item.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
			item.setAllPy(PinyinTools.getAllPinYin(displayName));
			item.setSort(PinyinTools.getSort(displayName));
			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}

	/**
	 * 根据搜索条件(电话或姓名匹配)获取联系人(只有联系人id、电话号码和名称) 同一个联系人多个号码情况会不会返回该联系人下的所有号码
	 * 
	 * @param mContext
	 * @param where
	 * @return
	 */
	public static Contact getContactByNumbersOrName(Context mContext, String where) {
		Contact item = null;
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join  "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME, null);

		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			// if(phoneNumber==null || phoneNumber.length()==0) continue;
			if (phoneNumber.equals(where) || displayName.equals(where)) {
				item = new Contact();
				item.setUserid("" + contact_id);
				item.setDisplayName(displayName);
				item.setLinkPhone(phoneNumber);
				item.setCommonContact(isCommon == 0 ? false : true);
				break;
			}
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return item;
	}

	/**
	 * 根据搜索条件(电话或姓名匹配)获取联系人(只有联系人id、电话号码和名称) 同一个联系人下多个号码匹配，则返回不同Contact
	 * 
	 * @param mContext
	 * @param where
	 * @return
	 */
	public static List<Contact> getContactsByNumber(Context mContext, String where) {
		List<Contact> cntacts = new ArrayList<>();
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS_DATA.DATA + " like ? and " + APP_CONTACTS_DATA.TYPE
				+ " =? order by " + APP_CONTACTS.DISPLAY_NAME, new String[] { "%" + where + "%",
				"phone" });

		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			Contact item = new Contact();
			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setCommonContact(isCommon == 0 ? false : true);
			cntacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return cntacts;
	}

	/**
	 * 根据联系人电话返回联系人。 如果联系人多个号码，只获得第一个
	 * 
	 * @param context
	 * @param number
	 * @return
	 */
	public static Contact getContactByNumber(Context mContext, String phone) {
		if (StringUtil.isEmpty(phone)) {
			return null;
		}
		Contact item = null;
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS_DATA.DATA + "=? and " + APP_CONTACTS_DATA.TYPE + "=? "
				+ " order by " + APP_CONTACTS.DISPLAY_NAME, new String[] { phone, "phone" });

		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;
			item = new Contact();
			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setCommonContact(isCommon == 0 ? false : true);
			break;
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return item;
	}

	/**
	 * 获取所有联系人,可以显示重复联系人(只有联系人id、电话号码和名称) <br/>
	 * 联系人多个号码情况下，返回多个联系人(联系人id和姓名相同，号码不同)
	 * 
	 * @param mContext
	 * @return
	 */
	public static ArrayList<Contact> getContacts(Context mContext) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME, null);

		ArrayList<Contact> contacts = new ArrayList<Contact>();
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			Contact item = new Contact();
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}

			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;

			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setAllPy(PinyinTools.getAllPinYin(displayName));
			item.setCommonContact(isCommon == 0 ? false : true);
			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}

	/**
	 * 获取没有安装客户端的联系人,用于从服务端获取安装状态 联系人多个号码情况下，返回该联系人第一个号码和姓名，其他号码忽略
	 * 
	 * @param mContext
	 * @return
	 */
	public static Map<String, String> getUnInstallContacts(Context mContext) {
		Map<String, String> phones = getInstallPhone(mContext);

		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME, null);

		Map<String, String> contacts = new LinkedHashMap<String, String>();
		long lasteContactId = -1;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			if (lasteContactId == contact_id)
				continue;
			else
				lasteContactId = contact_id;

			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			// 非手机号码不添加
			if (!ValidUtil.isValidMobilePhoneNumber(phoneNumber))
				continue;

			if (phones != null && phones.size() > 0) {
				for (String p : phones.keySet()) {
					if (phoneNumber.equals(p)) {
						continue;
					} else {
						contacts.put(phoneNumber, displayName);
					}
				}
			} else {
				contacts.put(phoneNumber, displayName);
			}
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}

	/**
	 * 搜索本地联系人 <br/>
	 * 联系人多个号码情况下，返回该联系人第一个号码
	 * 
	 * @param mContext
	 * @param txt
	 * @return
	 */
	public static ArrayList<Contact> getContactsByWhere(Context mContext, String txt) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME, null);

		ArrayList<Contact> contacts = new ArrayList<Contact>();
		long lasteContactId = -1;
		Map<String, String> phones = getInstallPhone(mContext);
		while (cursor.moveToNext()) {
			// boolean isAdd=true;
			Contact item = new Contact();
			int contact_id = cursor.getInt(0);

			if (lasteContactId == contact_id)
				continue;
			else
				lasteContactId = contact_id;
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			item.setCommonContact(isCommon == 0 ? false : true);
			displayName = displayName == null ? phoneNumber : displayName;// 如果名称为空就显示电话号码
			// 得到联系人头像Bitamp
			Bitmap contactPhoto = null;
			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;

			// item.setContactPhoto(contactPhoto);

			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}

			for (String p : phones.keySet()) {
				if (phoneNumber.equals(p)) {
					item.setInstall(1);
					break;
				}
			}

			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);
			item.setSourceId("1");

			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;

			item.setUserid("" + contact_id);
			item.setDisplayName(displayName);
			item.setLinkPhone(phoneNumber);

			phoneNumber = phoneNumber.trim();
			String letter = PinyinTools.getShouPinYin(displayName.substring(0, 1));
			char[] letterChar = letter.toCharArray();
			if (letterChar != null && letterChar.length > 0) {
				int tenChar = letterChar[0];
				if (tenChar > 'a' && tenChar < 'z') {
					item.setLetter(letter.toUpperCase());
				} else if (tenChar > 'A' && tenChar < 'Z') {
					item.setLetter(letter);
				} else {
					item.setFirstPy("#");
				}
			} else {
				item.setFirstPy("#");
			}

			item.setAllPy(PinyinTools.getAllPinYin(displayName));
			item.setSort(PinyinTools.getSort(displayName));

			contacts.add(item);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();

		ArrayList<Contact> searcherContacts = new ArrayList<Contact>();
		String keyEncode = "";
		if (!StringUtil.isEmpty(txt)) {
			keyEncode = StringUtil.encode(txt);
			if (StringUtil.isNum(txt)) {
				// 数字
				for (Contact contact : contacts) {
					if (contact.getLinkPhone().contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			} else if (keyEncode.length() == txt.length()) {
				// 拼音
				String txtTmp = txt.toUpperCase();
				for (Contact contact : contacts) {
					if (contact.getAllPy().contains(txtTmp)) {
						searcherContacts.add(contact);
					} else if (contact.getFirstPy() != null
							&& contact.getFirstPy().contains(txtTmp)) {
						searcherContacts.add(contact);
					} else if (contact.getDisplayName() != null
							&& contact.getDisplayName().contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			} else {
				// 名称
				for (Contact contact : contacts) {
					if (contact.getDisplayName().replace(" ", "").contains(txt)) {
						searcherContacts.add(contact);
					}
				}
			}
		}
		return searcherContacts;
	}

	/**
	 * 根据联系人id删除联系人
	 * 
	 * @param mContext
	 * @param id
	 */
	public static void DeleteContacts(Context mContext, String id) {
		if (TextUtils.isEmpty(id)) {
			return;
		}
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		db.beginTransaction();
		try {
			db.delete(APP_CONTACTS_DATA.TABLE_NAME, APP_CONTACTS_DATA.CONTACTS_ID + "=?",
					new String[] { id });
			db.delete(APP_CONTACTS.TABLE_NAME, APP_CONTACTS.ID + "=?", new String[] { id });
			db.setTransactionSuccessful();
			Intent intent = new Intent(APP_CONTACT_CHNAGE);
			intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_REMOVE);
			intent.putExtra(APP_CONTACT_CHNAGE_ID, Integer.parseInt(id));
			mContext.sendBroadcast(intent);
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		DBManager.getInstance(mContext).closeDatabase();
	}

	/**
	 * 根据联系人id删除联系人
	 * 
	 * @param mContext
	 * @param id
	 */
	public static boolean deleteContacts(Context mContext, String id) {
		if (TextUtils.isEmpty(id)) {
			return false;
		}
		boolean isSuccess = true;
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		db.beginTransaction();
		try {
			db.delete(APP_CONTACTS_DATA.TABLE_NAME, APP_CONTACTS_DATA.CONTACTS_ID + "=?",
					new String[] { id });
			db.delete(APP_CONTACTS.TABLE_NAME, APP_CONTACTS.ID + "=?", new String[] { id });
			db.setTransactionSuccessful();
		} catch (Exception e) {
			isSuccess = false;
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		DBManager.getInstance(mContext).closeDatabase();
		if(isSuccess){
			Intent intent = new Intent(APP_CONTACT_CHNAGE);
			intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_REMOVE);
			intent.putExtra(APP_CONTACT_CHNAGE_ID, Integer.parseInt(id));
			mContext.sendBroadcast(intent);
		}
		return isSuccess;
	}
	
	/**
	 * 删除多个联系人
	 * 
	 * @param mContext
	 * @param contacts
	 */
	public static boolean deleteContacts(Context mContext, List<Contact> contacts) {
		if (contacts == null) {
			return false;
		}
		boolean isSuccess = true;
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		db.beginTransaction();
		ArrayList<String> ids = new ArrayList<String>();
		try {
			for (Contact contact : contacts) {
				String id = contact.getUserid();
				if (TextUtils.isEmpty(id)) {
					isSuccess = false;
					break;
				}
				ids.add(id);
				db.delete(APP_CONTACTS_DATA.TABLE_NAME, APP_CONTACTS_DATA.CONTACTS_ID + "=?",
					new String[] { id });
				db.delete(APP_CONTACTS.TABLE_NAME, APP_CONTACTS.ID + "=?", new String[] { id });
			}
			db.setTransactionSuccessful();
			
		} catch (Exception e) {
			isSuccess = false;
			e.printStackTrace();
		} finally {
			db.endTransaction();
		}
		if(isSuccess){
			DBManager.getInstance(mContext).closeDatabase();
			Intent intent = new Intent(APP_CONTACT_CHNAGE);
			intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_REMOVE_All);
			intent.putStringArrayListExtra(APP_CONTACT_CHNAGE_ID, ids);
			mContext.sendBroadcast(intent);
		}
		return isSuccess;
	}
	
	/**
	 * 根据名称查询
	 * 
	 * @param mContext
	 * @param name
	 * @param start
	 * @param count
	 * @return
	 */
	public static ArrayList<Contact> getContactsByName(Context mContext, String name, int start,
			int count) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS.DISPLAY_NAME + " like '%" + name + "%' order by "
				+ APP_CONTACTS.DISPLAY_NAME + " asc limit " + start + "," + count, null);

		ArrayList<Contact> contacts = new ArrayList<Contact>();
		while (cursor.moveToNext()) {
			Contact cc = new Contact();
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			cc.setUserid(contact_id+"");
			cc.setDisplayName(displayName);
			cc.setLinkPhone(phoneNumber);
			cc.setSourceId("1");// TODO ???
			cc.setCommonContact(isCommon==0?false:true);
			contacts.add(cc);
		}
		return contacts;
	}

	/**
	 * 获取所有安装客户端的联系人
	 * 
	 * @param mContext
	 * @return
	 */
	public static Map<String, String> getInstallPhone(Context mContext) {
		Map<String, String> installPhone = new HashMap<String, String>();
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery(" select * from install_table", null);
		while (cursor.moveToNext()) {
			String phone = cursor.getString(cursor.getColumnIndex("install_phone"));
			String name = cursor.getString(cursor.getColumnIndex("p_name"));
			installPhone.put(phone, name);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return installPhone;
	}

	/**
	 * 搜索已经安装客户端的用户
	 * 
	 * @param mContext
	 * @param phones
	 * @param contact
	 */
	public static Map<String, String> getInstallPhoneByName(Context mContext, String keywrod) {
		Map<String, String> installPhone = new HashMap<String, String>();
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery(" select * from install_table where p_name like '%" + keywrod
				+ "%'", null);
		while (cursor.moveToNext()) {
			String phone = cursor.getString(cursor.getColumnIndex("install_phone"));
			String name = cursor.getString(cursor.getColumnIndex("p_name"));
			installPhone.put(phone, name);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return installPhone;
	}

	/**
	 * 添加安装客户端用户
	 * 
	 * @param mContext
	 * @param phones
	 * @param contact
	 */
	public static void addInstallPhone(Context mContext, ArrayList<String> phones,
			Map<String, String> contact) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		// db.execSQL("delete from install_table");//添加前把表的内容删除
		for (String p : phones) {
			db.execSQL("insert into install_table ( install_phone ,p_name) values ('" + p + "','"
					+ contact.get(p) + "')");
		}
		DBManager.getInstance(mContext).closeDatabase();

	}

	/**
	 * 从服务端获取本地联系人还有哪些人已经安装客户端
	 * 
	 * @param mContext
	 */
	public static boolean getUnInstallStatusOfContact(final Context mContext) {
		long lastedtime = SharedPreferencesUtil.getLong(mContext, "getinstallStatus");
		long nowTime = new Date().getTime();
		if (lastedtime != -1 && (nowTime - lastedtime) < 86400000) {
			return true;
		}
		Map<String, String> sContacts = getUnInstallContacts(mContext);
		LoadUnInstall loader = new LoadUnInstall(mContext, null, sContacts);
		if (loader.loadInstall()) {
			SharedPreferencesUtil.putLong(mContext, "getinstallStatus", nowTime);
			// 获取这些未安装的安装状态
			return true;
		}
		return false;
	}

	/**
	 * 获取所有联系人，返回json字符串
	 */
	public static ArrayList<UserCard> getAllRecords(Context mContext) {
		ArrayList<Contact> result = null;
		result = getAllContacts(mContext);
		ArrayList<UserCard> users = new ArrayList<>();

		for (Contact contact : result) {
			UserCard item = new UserCard();
			item.setMoblie(contact.getLinkPhone());
			item.setName(contact.getDisplayName());
			users.add(item);
		}

		return users;
	}

	/**
	 * 获取所有联系人电话（key）和姓名，返回Map 
	 * 注意：如果相同联系人下多个号码，第一个号码键值对，该方法有缺陷
	 * @param context
	 * @return
	 */
	public static Map<String, String> getContactPhoneNameMap(Context mContext) {
		Map<String, String> map = new HashMap<String, String>();
		Cursor cursor = null;
		try {
			SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
			cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
					+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
					+ APP_CONTACTS.DISPLAY_NAME, null);

			long lasteContactId = -1;
			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					String displayName = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
					String phoneNumber = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS_DATA.DATA));
					int contact_id = cursor.getInt(0);
					if (lasteContactId == contact_id)
						continue;
					else
						lasteContactId = contact_id;

					// 去空格
					if (phoneNumber.contains(" ")) {
						phoneNumber = phoneNumber.replace(" ", "");
					}
					// 去横杠
					if (phoneNumber.contains("-")) {
						phoneNumber = phoneNumber.replace("-", "");
					}
					// 去“+86”前缀
					if (phoneNumber.contains("+86")) {
						phoneNumber = phoneNumber.replace("+86", "");
					}

					if (StringUtil.isEmpty(displayName)) {
						displayName = phoneNumber;
					}
					if (!map.containsKey(phoneNumber)) {
						map.put(phoneNumber, displayName);
					}

				}
			}
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			DBManager.getInstance(mContext).closeDatabase();
		}
		return map;

	}

	/**
	 * 获取所有联系人电话（key）和姓名，返回Map
	 * 如果相同联系人下多个号码，返回多个键值对
	 * @param context
	 * @return
	 */
	public static Map<String, String> getContactAllPhoneNameMap(Context mContext) {
		Map<String, String> map = new HashMap<String, String>();
		Cursor cursor = null;
		try {
			SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
			cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
					+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
					+ APP_CONTACTS.DISPLAY_NAME, null);

			if (cursor != null && cursor.getCount() > 0) {
				while (cursor.moveToNext()) {
					String displayName = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
					String phoneNumber = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS_DATA.DATA));

					// 去空格
					if (phoneNumber.contains(" ")) {
						phoneNumber = phoneNumber.replace(" ", "");
					}
					// 去横杠
					if (phoneNumber.contains("-")) {
						phoneNumber = phoneNumber.replace("-", "");
					}
					// 去“+86”前缀
					if (phoneNumber.contains("+86")) {
						phoneNumber = phoneNumber.replace("+86", "");
					}

					if (StringUtil.isEmpty(displayName)) {
						displayName = phoneNumber;
					}
					if (!map.containsKey(phoneNumber)) {
						map.put(phoneNumber, displayName);
					}
				}
			}
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			DBManager.getInstance(mContext).closeDatabase();
		}
		return map;

	}

	/**
	 * 获得联系人下所有的手机号码
	 * 
	 * @param mContext
	 * @param userId
	 * @return
	 */
	public static List<String> getPhones(Context mContext, String userId) {
		List<String> phones = new LinkedList<>();
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS_DATA.TABLE_NAME + " where "
				+ APP_CONTACTS_DATA.CONTACTS_ID + "=? and " + APP_CONTACTS_DATA.TYPE + "=?",
				new String[] { userId, "phone" });

		while (cursor.moveToNext()) {
			// 遍历所有的联系人下面所有的电话号码
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			phones.add(phoneNumber);
		}
		if (cursor != null) {
			cursor.close();
		}
		DBManager.getInstance(mContext).closeDatabase();
		return phones;
	}

	/**
	 * 根据电话号码查询联系人，可能会查到多个联系人，但只返回一个
	 * 
	 * @param mContext
	 * @param phone
	 * @return
	 */
	public static Contact getLocalContactByPhone(Context mContext, String phone) {
		if (StringUtil.isEmpty(phone)) {
			return null;
		}
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS_DATA.DATA + "=? and " + APP_CONTACTS_DATA.TYPE + "=? " + "order by "
				+ APP_CONTACTS.DISPLAY_NAME, new String[] { phone, "phone" });
		Contact contact = null;
		try {
			if (cursor != null) {
				if (cursor.moveToNext()) {
					contact = new Contact();
					String displayName = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
					String phoneNumber = cursor.getString(cursor
							.getColumnIndex(APP_CONTACTS_DATA.DATA));
					int contact_id = cursor.getInt(0);
					int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
					contact.setCommonContact(isCommon==0?false:true);
					contact.setLinkPhone(phoneNumber);
					contact.setDisplayName(displayName);
					contact.setUserid(contact_id + "");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			DBManager.getInstance(mContext).closeDatabase();
		}
		return contact;
	}

	/**
	 * 根据contactId查询联系人
	 * 联系人有多个号码情况下返回一个号码
	 * @param mContext
	 * @param contactId
	 * @return
	 */
	public static Contact getContact(Context mContext, String contactId) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();

		Cursor cursor = null;
		Contact item = new Contact();
		try {
			cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
					+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where c._id =? "
					+ "order by " + APP_CONTACTS.DISPLAY_NAME, new String[] { contactId });
			long lasteContactId = -1;
			while (cursor.moveToNext()) {
				String displayName = cursor.getString(cursor
						.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
				String phoneNumber = cursor
						.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
				int contact_id = cursor.getInt(0);
				int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
				if (lasteContactId == contact_id)
					continue;
				else
					lasteContactId = contact_id;
				if (phoneNumber.contains(" ")) {
					phoneNumber = phoneNumber.replace(" ", "");
				}
				// 去横杠
				if (phoneNumber.contains("-")) {
					phoneNumber = phoneNumber.replace("-", "");
				}
				// 去“+86”前缀
				if (phoneNumber.contains("+86")) {
					phoneNumber = phoneNumber.replace("+86", "");
				}
				// item.setInstall(1);
				if (phoneNumber == null || phoneNumber.length() == 0)
					continue;

				item.setUserid("" + contact_id);
				item.setDisplayName(displayName);
				item.setLinkPhone(phoneNumber);
				item.setCommonContact(isCommon==0?false:true);

				if (StringUtil.isEmpty(displayName)) {
					item.setLetter("#");
				} else {
					displayName = displayName.trim();
					String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar = letter.toCharArray();
					if (firstChar != null && firstChar.length > 0) {
						if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
							item.setLetter(letter.toUpperCase());
						} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
							item.setLetter(letter);
						} else {
							item.setLetter("#");
						}
					} else {
						item.setLetter("#");
					}
				}
				item.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				item.setAllPy(PinyinTools.getAllPinYin(displayName));
				item.setSort(PinyinTools.getSort(displayName));
			}

		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		} finally {
			if (cursor != null)
				cursor.close();
			DBManager.getInstance(mContext).closeDatabase();
		}

		return item;
	}

	/**
	 * 插入联系人
	 * 
	 * @param context
	 * @param displayName
	 *            联系人姓名
	 * @param phones
	 *            联系人电话
	 * @return 是否插入成功
	 */
	public static boolean saveAppContact(Context context, String displayName, List<String> phones) {
		return saveAppContact(context, displayName, phones, false);
	}

	public static boolean saveAppContact(Context context, String displayName, List<String> phones,
			boolean isComm) {
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put(AppDbHelper.APP_CONTACTS.DISPLAY_NAME, displayName);
			values.put(AppDbHelper.APP_CONTACTS.IS_COMMON_CONTACT, isComm ? 1 : 0);
			long rowId = getContactIdByName(context, displayName);
			if (rowId == -1) {
				rowId = db.insert(AppDbHelper.APP_CONTACTS.TABLE_NAME, null, values);
			} else if (isComm) {
				addCommonContact(context, (int) rowId);
			}
			if (rowId != -1) {// 联系人信息插入成功
				for (String phone : phones) {
					if (TextUtils.isEmpty(phone)) {// 电话号码为空时，略过
						continue;
					}
					ContentValues phoneValues = new ContentValues();
					phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.DATA, phone);
					phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.CONTACTS_ID, rowId);
					phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.TYPE, "phone");
					long phoneRowId = db.insert(AppDbHelper.APP_CONTACTS_DATA.TABLE_NAME, null,
							phoneValues);
					if (phoneRowId == -1) {// 联系人电话插入失败
						result = false;
						break;
					}
				}
				if (result) {
					db.setTransactionSuccessful();
					Intent intent = new Intent(APP_CONTACT_CHNAGE);
					intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_ADD);
					intent.putExtra(APP_CONTACT_CHNAGE_ID, (int) rowId);
					context.sendBroadcast(intent);
				}
			} else {
				result = false;
			}
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			db.endTransaction();
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	/**
	 * 修改联系人信息
	 * 
	 * @param context
	 * @param userId
	 * @param displayName
	 * @param phones
	 * @return
	 */
	public static boolean editChange(Context context, int userId, String displayName,
			List<String> phones) {
		if (!isExistContactId(context, userId)) {// 如果联系人不存在，直接保存
			return saveAppContact(context, displayName, phones);
		}

		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		db.beginTransaction();
		try {
			ContentValues values = new ContentValues();
			values.put(AppDbHelper.APP_CONTACTS.DISPLAY_NAME, displayName);
			db.update(AppDbHelper.APP_CONTACTS.TABLE_NAME, values, APP_CONTACTS.ID + "=?",
					new String[] { userId + "" });
			db.delete(APP_CONTACTS_DATA.TABLE_NAME, APP_CONTACTS_DATA.CONTACTS_ID + "=?",
					new String[] { userId + "" });

			for (String phone : phones) {
				if (TextUtils.isEmpty(phone)) {// 电话号码为空时，略过
					continue;
				}
				phone = phone.trim();
				ContentValues phoneValues = new ContentValues();
				phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.DATA, phone);
				phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.CONTACTS_ID, userId);
				phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.TYPE, "phone");
				long phoneRowId = db.insert(AppDbHelper.APP_CONTACTS_DATA.TABLE_NAME, null,
						phoneValues);
				if (phoneRowId == -1) {// 联系人电话插入失败
					result = false;
					break;
				}
			}
			if (result) {
				db.setTransactionSuccessful();
				Intent intent = new Intent(APP_CONTACT_CHNAGE);
				intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_UPDATE);
				intent.putExtra(APP_CONTACT_CHNAGE_ID, userId);
				context.sendBroadcast(intent);
			}
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			db.endTransaction();
			DBManager.getInstance(context).closeDatabase();
		}
		return result;

	}

	/**
	 * 插入联系人
	 * 
	 * @param context
	 * @param displayName
	 *            联系人姓名
	 * @param phone
	 *            联系人电话
	 * @return 是否插入成功
	 */
	public static boolean saveAppContact(Context context, String displayName, String phone) {
		ArrayList<String> phones = new ArrayList<String>();
		phones.add(phone);
		return saveAppContact(context, displayName, phones);
	}

	/**
	 * 判断是联系人姓名否存在通讯录种
	 * 
	 * @param context
	 * @param displayName
	 *            要查找的联系人姓名
	 * @return false 联系人不存在 ; true 联系人存在
	 */
	public static boolean isExistContact(Context context, String displayName) {
		boolean isExist = false;
		if (TextUtils.isEmpty(displayName)) {// 姓名为空时，直接返回true
			return true;
		}
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + AppDbHelper.APP_CONTACTS.TABLE_NAME
				+ " where " + AppDbHelper.APP_CONTACTS.DISPLAY_NAME + "=? ",
				new String[] { displayName });
		if (cursor.getCount() != 0) {
			isExist = true;
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(context).closeDatabase();
		return isExist;
	}

	/**
	 * 判断是联系人id否存在通讯录中
	 * 
	 * @param context
	 * @param displayName
	 *            要查找的联系人姓名
	 * @return false 联系人不存在 ; true 联系人存在
	 */
	public static boolean isExistContactId(Context context, int userId) {
		boolean isExist = false;
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + AppDbHelper.APP_CONTACTS.TABLE_NAME
				+ " where " + AppDbHelper.APP_CONTACTS.ID + "=? ", new String[] { userId + "" });
		if (cursor.getCount() != 0) {
			isExist = true;
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(context).closeDatabase();
		return isExist;
	}

	/**
	 * 根据姓名返回联系人id
	 * 
	 * @param context
	 * @param displayName
	 * @return
	 */
	public static int getContactIdByName(Context context, String displayName) {
		int id = -1;
		if (TextUtils.isEmpty(displayName)) {// 姓名为空时，直接返回true
			return -1;
		}
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + AppDbHelper.APP_CONTACTS.TABLE_NAME
				+ " where " + AppDbHelper.APP_CONTACTS.DISPLAY_NAME + "=? ",
				new String[] { displayName });
		if (cursor.moveToFirst()) {
			id = cursor.getInt(cursor.getColumnIndex(AppDbHelper.APP_CONTACTS.ID));
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(context).closeDatabase();
		return id;
	}

	/**
	 * 根据联系人电话返回联系人id，查询到的联系人可能有多条，但只返回第一条
	 * 
	 * @param context
	 * @param number
	 * @return
	 */
	public static String getContactIdByNumber(Context mContext, String phone) {
		if (StringUtil.isEmpty(phone)) {
			return null;
		}
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		String id = null;
		Cursor cursor = null;
		try {
			cursor = db.rawQuery("select * from " + APP_CONTACTS_DATA.TABLE_NAME, null);
			while (cursor.moveToNext()) {
				String phoneNumber = cursor
						.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
				int contact_id = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS_DATA.ID));
				if (PhoneNumberUtils.compare(phone, phoneNumber)) {
					id = String.valueOf(contact_id);
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (cursor != null) {
				cursor.close();
			}
			DBManager.getInstance(mContext).closeDatabase();
		}
		return id;
	}

	/**
	 * 将本地数据库的联系人保存到自己联系人数据库
	 * 
	 * @param context
	 * @param contacts
	 *            从本地获得的联系人，必须有DisplayName和Userid
	 * @return 是否全部插入成功，true表示成功
	 */
	public static boolean saveAllContact(Context context, List<Contact> contacts) {
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		db.beginTransaction();
		try {
			for (Contact contact : contacts) {
				// WriteLog.WriteLocationListLogSDK("contact","---------------------------");
				if (contact == null || TextUtils.isEmpty(contact.getDisplayName())
						|| TextUtils.isEmpty(contact.getUserid())) {// 略过不符合的数据
					continue;
				}
				// WriteLog.WriteLocationListLogSDK("contact",
				// contact.getLinkPhone() + " = " +contact.getDisplayName());
				// @SuppressWarnings("deprecation")
				// List<String> phones =
				// SysContactDao.getSystemContactPhones(context,contact.getUserid());//
				// 获得联系人的所有号码
				List<String> phones = contact.getPhoneList();
				// WriteLog.WriteLocationListLogSDK("contact",phones.toString());
				List<String> tempPhones = new ArrayList<>();
				for (String phone : phones) {
					phone = phone.trim();
					if (!isExistPhone(context, phone)) {
						tempPhones.add(phone);
					}
				}
				// WriteLog.WriteLocationListLogSDK("contact",tempPhones.toString());
				if (tempPhones.size() == 0) {
					continue;
				}

				// 先从本地数据库判断是否存在相同名字的联系人
				long rowId = getContactIdByName(context, contact.getDisplayName());
				if (rowId == -1) {// 不存在，则新建一个联系人
					ContentValues values = new ContentValues();
					values.put(AppDbHelper.APP_CONTACTS.DISPLAY_NAME, contact.getDisplayName());
					rowId = db.insert(AppDbHelper.APP_CONTACTS.TABLE_NAME, null, values);
					// WriteLog.WriteLocationListLogSDK("contact","insert");
				}
				// WriteLog.WriteLocationListLogSDK("contact",rowId + " ");
				if (rowId != -1) {// 联系人信息插入成功
					for (String phone : tempPhones) {
						// WriteLog.WriteLocationListLogSDK("contact",phone +
						// "-"+rowId);
						if (TextUtils.isEmpty(phone)) {// 电话号码为空时，略过
							continue;
						}
						ContentValues phoneValues = new ContentValues();
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.DATA, phone);
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.CONTACTS_ID, rowId);
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.TYPE, "phone");
						long phoneRowId = db.insert(AppDbHelper.APP_CONTACTS_DATA.TABLE_NAME, null,
								phoneValues);
						// WriteLog.WriteLocationListLogSDK("contact",phoneRowId+"");
						if (phoneRowId == -1) {// 联系人电话插入失败
							result = false;
							break;
						}
					}
					if (!result) {// 插入联系人号码失败
						break;
					}
				} else {
					result = false;
					break;
				}
			}
			if (result) {
				db.setTransactionSuccessful();
				Intent intent = new Intent(APP_CONTACT_CHNAGE);
				intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_BACHADD);
				context.sendBroadcast(intent);
			}
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			db.endTransaction();
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	/**
	 * 获得联系人电话号码和名称map,同一个联系人可能有多个 map key:phoneNumber + "_" + displayName
	 * value:"" 这个方法为了替换com.robin.phone.contact.utils.DownloadContactUtils.
	 * getContactsMap(Context)
	 * 
	 * @param mContext
	 * @return
	 */
	public static Set<String> getContactsMap(Context mContext) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME, null);

		Set<String> contacts = new HashSet<String>();
		if (cursor != null) {
			while (cursor.moveToNext()) {
				String displayName = cursor.getString(cursor
						.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
				String phoneNumber = cursor
						.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));

				if (!TextUtils.isEmpty(phoneNumber)) {
					if (phoneNumber.contains(" ")) {
						phoneNumber = phoneNumber.replace(" ", "");
					}

					if (phoneNumber.contains("-")) {
						phoneNumber = phoneNumber.replace("-", "");
					}

					if (phoneNumber.contains("+86")) {
						phoneNumber = phoneNumber.replace("+86", "");
					}
					contacts.add(phoneNumber + "_" + displayName);
				}
			}
			cursor.close();
		}
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}

	/**
	 * 批量添加通讯录
	 * 
	 * @throws OperationApplicationException
	 * @throws RemoteException
	 */
	public static BatchAddContactResult batchAddContact(Context context, Set<String> cmap,
			Set<String> map) throws RemoteException, OperationApplicationException {
		BatchAddContactResult result = new BatchAddContactResult();
		result.setSuccess(true);
		result.setTotalPhone(map.size());

		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		db.beginTransaction();
		try {
			for (String key : map) {
				if (!cmap.contains(key)) {
					String phone = key.substring(0, key.indexOf("_"));
					String name = key.substring(key.indexOf("_") + 1);

					if (TextUtils.isEmpty(phone)) {// 略过不符合的数据
						result.setInvalidPhone(result.getInvalidPhone() + 1);
						continue;
					}

					phone = phone.trim();
					if (isExistPhone(context, phone)) {// 忽略已经存在的号码
						result.setRepeatPhone(result.getRepeatPhone() + 1);
						continue;
					}

					if (TextUtils.isEmpty(name.trim())) {// 如果姓名为空，使用电话号码充当姓名
						name = phone;
					}

					// 先从本地数据库判断是否存在相同名字的联系人
					long rowId = getContactIdByName(context, name);
					if (rowId == -1) {// 不存在，则新建一个联系人
						ContentValues values = new ContentValues();
						values.put(AppDbHelper.APP_CONTACTS.DISPLAY_NAME, name);
						rowId = db.insert(AppDbHelper.APP_CONTACTS.TABLE_NAME, null, values);
					}
					if (rowId != -1) {// 联系人信息插入成功
						ContentValues phoneValues = new ContentValues();
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.DATA, phone);
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.CONTACTS_ID, rowId);
						phoneValues.put(AppDbHelper.APP_CONTACTS_DATA.TYPE, "phone");
						long phoneRowId = db.insert(AppDbHelper.APP_CONTACTS_DATA.TABLE_NAME, null,
								phoneValues);
						if (phoneRowId == -1) {// 联系人电话插入失败
							result.setSuccess(false);
							;
							break;
						}
						result.setSavePhone(result.getSavePhone() + 1);
					} else {
						result.setSuccess(false);
						break;
					}
				} else {
					result.setRepeatPhone(result.getRepeatPhone() + 1);
				}
			}
			if (result.isSuccess()) {
				db.setTransactionSuccessful();
				Intent intent = new Intent(APP_CONTACT_CHNAGE);
				intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_BACHADD);
				context.sendBroadcast(intent);
			}
		} catch (Exception e) {
			// TODO 写日志
			result.setSuccess(false);
			e.printStackTrace();
		} finally {
			db.endTransaction();
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	/**
	 * 根据联系人id获得联系人信息（姓名和多个号码）
	 * 
	 * @param mContext
	 * @return
	 */
	public static Contact getContactById(Context mContext, int contactId) {
		if (contactId < 0) {
			return null;
		}
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join  "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where c._id = ?",
				new String[] { String.valueOf(contactId) });

		Contact contact = new Contact();
		ArrayList<String> phones = new ArrayList<>();
		boolean isFirst = false;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (TextUtils.isEmpty(phoneNumber))
				continue;

			phones.add(phoneNumber);

			if (!isFirst) {
				isFirst = true;
				contact.setUserid("" + contactId);
				contact.setDisplayName(displayName);
				contact.setCommonContact(isCommon==0?false:true);
				if (StringUtil.isEmpty(displayName)) {
					contact.setLetter("#");
				} else {
					displayName = displayName.trim();
					String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar = letter.toCharArray();
					if (firstChar != null && firstChar.length > 0) {
						if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
							contact.setLetter(letter.toUpperCase());
						} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
							contact.setLetter(letter);
						} else {
							contact.setLetter("#");
						}
					} else {
						contact.setLetter("#");
					}
				}
				contact.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				contact.setAllPy(PinyinTools.getAllPinYin(displayName));
				contact.setSort(PinyinTools.getSort(displayName));
			}
			contact.setPhoneList(phones);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contact;
	}

	/**
	 * 根据获得联系人全部信息（姓名和多个号码）
	 * 
	 * @param mContext
	 * @return
	 */
	public static List<Contact> getContactWithAllPhone(Context mContext) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join  "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id order by "
				+ APP_CONTACTS.DISPLAY_NAME + "," + APP_CONTACTS_DATA.DATA, null);

		List<Contact> contacts = new ArrayList<Contact>();
		Contact contact = new Contact();
		ArrayList<String> phones = new ArrayList<>();
		int lastId = -1;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// String phoneEmail =
			// cursor.getString(cursor.getColumnIndex(APP_CONTACTS.EMAIL_ADDREDD));
			int contactId = cursor.getInt(0);

			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (TextUtils.isEmpty(phoneNumber))
				continue;

			if (lastId != contactId) {
				if (lastId != -1) {
					contact.setPhoneList(phones);
					contacts.add(contact);
					contact = new Contact();
					phones = new ArrayList<>();
				}
				contact.setUserid("" + contactId);
				contact.setDisplayName(displayName);
				contact.setLinkPhone(phoneNumber);
				contact.setCommonContact(isCommon == 0 ? false : true);
				if (StringUtil.isEmpty(displayName)) {
					contact.setLetter("#");
				} else {
					displayName = displayName.trim();
					String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar = letter.toCharArray();
					if (firstChar != null && firstChar.length > 0) {
						if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
							contact.setLetter(letter.toUpperCase());
						} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
							contact.setLetter(letter);
						} else {
							contact.setLetter("#");
						}
					} else {
						contact.setLetter("#");
					}
				}
				contact.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				contact.setAllPy(PinyinTools.getAllPinYin(displayName));
				contact.setSort(PinyinTools.getSort(displayName));
				// contact.setEmail(phoneEmail);
			}
			phones.add(phoneNumber);
			lastId = contactId;
		}
		if (lastId != -1) {
			contact.setPhoneList(phones);
			contacts.add(contact);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}

	/**
	 * 根据contactId查询联系人（姓名和多个号码）
	 * 
	 * @param mContext
	 * @param contactId
	 * @return
	 */
	public static Contact getContactWithAllPhone(Context mContext, int contactId) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = null;
		Contact item = new Contact();
		try {
			cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
					+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where c._id =? "
					+ "order by " + APP_CONTACTS.DISPLAY_NAME + "," + APP_CONTACTS_DATA.DATA,
					new String[] { String.valueOf(contactId) });
			List<String> phones = new ArrayList<>();
			boolean isFirst = true;
			while (cursor.moveToNext()) {
				String displayName = cursor.getString(cursor
						.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
				String phoneNumber = cursor
						.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
				int contact_id = cursor.getInt(0);
				int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
				if (phoneNumber.contains(" ")) {
					phoneNumber = phoneNumber.replace(" ", "");
				}
				// 去横杠
				if (phoneNumber.contains("-")) {
					phoneNumber = phoneNumber.replace("-", "");
				}
				// 去“+86”前缀
				if (phoneNumber.contains("+86")) {
					phoneNumber = phoneNumber.replace("+86", "");
				}
				// item.setInstall(1);
				if (phoneNumber == null || phoneNumber.length() == 0)
					continue;

				if (isFirst) {
					item.setUserid("" + contact_id);
					item.setDisplayName(displayName);
					item.setLinkPhone(phoneNumber);
					item.setCommonContact(isCommon==0?false:true);
					if (StringUtil.isEmpty(displayName)) {
						item.setLetter("#");
					} else {
						displayName = displayName.trim();
						String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
						char[] firstChar = letter.toCharArray();
						if (firstChar != null && firstChar.length > 0) {
							if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
								item.setLetter(letter.toUpperCase());
							} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
								item.setLetter(letter);
							} else {
								item.setLetter("#");
							}
						} else {
							item.setLetter("#");
						}
					}
					item.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
					item.setAllPy(PinyinTools.getAllPinYin(displayName));
					item.setSort(PinyinTools.getSort(displayName));
					isFirst = false;
				}
				phones.add(phoneNumber);
			}
			item.setPhoneList(phones);
		} catch (Exception e) {
			// TODO
			e.printStackTrace();
		} finally {
			if (cursor != null)
				cursor.close();
			DBManager.getInstance(mContext).closeDatabase();
		}

		return item;
	}

	/**
	 * 根据联系人电话返回联系人（姓名和多个号码）
	 * 
	 * @param context
	 * @param number
	 * @return
	 */
	public static Contact getContactByNumberWithAllPhone(Context mContext, String phone) {
		if (StringUtil.isEmpty(phone)) {
			return null;
		}
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS_DATA.TYPE + "=? and c._id = (select "
				+ APP_CONTACTS_DATA.CONTACTS_ID + " from " + APP_CONTACTS_DATA.TABLE_NAME
				+ " where " + APP_CONTACTS_DATA.DATA + " = ? limit 0,1) " + " order by "
				+ APP_CONTACTS.DISPLAY_NAME, new String[] { "phone", phone });
		Contact item = new Contact();
		List<String> phones = new ArrayList<>();
		boolean isFirst = true;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			int contact_id = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (phoneNumber == null || phoneNumber.length() == 0)
				continue;
			if (isFirst) {
				item.setUserid("" + contact_id);
				item.setDisplayName(displayName);
				item.setLinkPhone(phoneNumber);
				item.setCommonContact(isCommon == 0 ? false : true);
				isFirst = false;
			}
			phones.add(phoneNumber);
		}
		item.setPhoneList(phones);
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return item;
	}

	/**
	 * 判断是联系人号码否存在通讯录中
	 * 
	 * @param context
	 * @param phone
	 *            要查找的联系人号码
	 * @return false 联系人不存在 ; true 联系人存在
	 */
	public static boolean isExistPhone(Context context, String phone) {
		boolean isExist = false;
		if (TextUtils.isEmpty(phone)) {// 号码为空时，直接返回true
			return true;
		}
		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + AppDbHelper.APP_CONTACTS_DATA.TABLE_NAME
				+ " where " + AppDbHelper.APP_CONTACTS_DATA.DATA + "=? and "
				+ AppDbHelper.APP_CONTACTS_DATA.TYPE + "=? ", new String[] { phone, "phone" });
		if (cursor.getCount() != 0) {
			isExist = true;
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(context).closeDatabase();
		return isExist;
	}

	public static class BatchAddContactResult {
		private boolean isSuccess = false;
		private int totalPhone = 0;
		private int savePhone = 0;
		private int invalidPhone = 0;
		private int repeatPhone = 0;

		public boolean isSuccess() {
			return isSuccess;
		}

		public void setSuccess(boolean isSuccess) {
			this.isSuccess = isSuccess;
		}

		public int getTotalPhone() {
			return totalPhone;
		}

		public void setTotalPhone(int totalPhone) {
			this.totalPhone = totalPhone;
		}

		public int getSavePhone() {
			return savePhone;
		}

		public void setSavePhone(int savePhone) {
			this.savePhone = savePhone;
		}

		public int getInvalidPhone() {
			return invalidPhone;
		}

		public void setInvalidPhone(int invalidPhone) {
			this.invalidPhone = invalidPhone;
		}

		public int getRepeatPhone() {
			return repeatPhone;
		}

		public void setRepeatPhone(int repeatPhone) {
			this.repeatPhone = repeatPhone;
		}
	}

	public static boolean addCommonContact(Context context, int userId) {

		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		try {
			ContentValues values = new ContentValues();
			values.put(AppDbHelper.APP_CONTACTS.IS_COMMON_CONTACT, 1);
			db.update(AppDbHelper.APP_CONTACTS.TABLE_NAME, values, APP_CONTACTS.ID + "=?",
					new String[] { userId + "" });
			Intent intent = new Intent(APP_CONTACT_CHNAGE);
			intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
			intent.putExtra(APP_CONTACT_CHNAGE_ID, userId);
			context.sendBroadcast(intent);
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	public static boolean deleteCommonContact(Context context, int userId) {

		SQLiteDatabase db = DBManager.getInstance(context).openDatabase();
		boolean result = true;
		try {
			ContentValues values = new ContentValues();
			values.put(AppDbHelper.APP_CONTACTS.IS_COMMON_CONTACT, 0);
			db.update(AppDbHelper.APP_CONTACTS.TABLE_NAME, values, APP_CONTACTS.ID + "=?",
					new String[] { userId + "" });
			Intent intent = new Intent(APP_CONTACT_CHNAGE);
			intent.putExtra(APP_CONTACT_CHNAGE_TYPE, APP_CONTACT_CHNAGE_TYPE_UPDATE_COMMON);
			intent.putExtra(APP_CONTACT_CHNAGE_ID, userId);
			context.sendBroadcast(intent);
		} catch (Exception e) {
			// TODO 写日志
			result = false;
			e.printStackTrace();
		} finally {
			DBManager.getInstance(context).closeDatabase();
		}
		return result;
	}

	/**
	 * 根据获得联系人常用联系人信息（姓名和多个号码）
	 * 
	 * @param mContext
	 * @return
	 */
	public static List<Contact> getCommonContactWithAllPhone(Context mContext) {
		SQLiteDatabase db = DBManager.getInstance(mContext).openDatabase();
		Cursor cursor = db.rawQuery("select * from " + APP_CONTACTS.TABLE_NAME + " c left join  "
				+ APP_CONTACTS_DATA.TABLE_NAME + " cd on c._id = cd.contact_id where "
				+ APP_CONTACTS.IS_COMMON_CONTACT + "=1 order by " + APP_CONTACTS.DISPLAY_NAME + ","
				+ APP_CONTACTS_DATA.DATA, null);

		List<Contact> contacts = new ArrayList<Contact>();
		Contact contact = new Contact();
		ArrayList<String> phones = new ArrayList<>();
		int lastId = -1;
		while (cursor.moveToNext()) {
			String displayName = cursor.getString(cursor.getColumnIndex(APP_CONTACTS.DISPLAY_NAME));
			String phoneNumber = cursor.getString(cursor.getColumnIndex(APP_CONTACTS_DATA.DATA));
			// String phoneEmail =
			// cursor.getString(cursor.getColumnIndex(APP_CONTACTS.EMAIL_ADDREDD));
			int contactId = cursor.getInt(0);
			int isCommon = cursor.getInt(cursor.getColumnIndex(APP_CONTACTS.IS_COMMON_CONTACT));
			// 去空格
			if (phoneNumber.contains(" ")) {
				phoneNumber = phoneNumber.replace(" ", "");
			}
			// 去横杠
			if (phoneNumber.contains("-")) {
				phoneNumber = phoneNumber.replace("-", "");
			}
			// 去“+86”前缀
			if (phoneNumber.contains("+86")) {
				phoneNumber = phoneNumber.replace("+86", "");
			}
			if (TextUtils.isEmpty(phoneNumber))
				continue;

			if (lastId != contactId) {
				if (lastId != -1) {
					contact.setPhoneList(phones);
					contacts.add(contact);
					contact = new Contact();
					phones = new ArrayList<>();
				}
				contact.setUserid("" + contactId);
				contact.setDisplayName(displayName);
				contact.setLinkPhone(phoneNumber);
				contact.setCommonContact(isCommon == 0 ? false : true);
				if (StringUtil.isEmpty(displayName)) {
					contact.setLetter("#");
				} else {
					displayName = displayName.trim();
					String letter = PinyinTools.getFirstCharPinYin(displayName.substring(0, 1));
					char[] firstChar = letter.toCharArray();
					if (firstChar != null && firstChar.length > 0) {
						if (firstChar[0] >= 'a' && firstChar[0] <= 'z') {
							contact.setLetter(letter.toUpperCase());
						} else if (firstChar[0] >= 'A' && firstChar[0] <= 'Z') {
							contact.setLetter(letter);
						} else {
							contact.setLetter("#");
						}
					} else {
						contact.setLetter("#");
					}
				}
				contact.setFirstPy(PinyinTools.getFirstCharPinYin(displayName));
				contact.setAllPy(PinyinTools.getAllPinYin(displayName));
				contact.setSort(PinyinTools.getSort(displayName));
				// contact.setEmail(phoneEmail);
			}
			phones.add(phoneNumber);
			lastId = contactId;
		}
		if (lastId != -1) {
			contact.setPhoneList(phones);
			contacts.add(contact);
		}
		if (cursor != null)
			cursor.close();
		DBManager.getInstance(mContext).closeDatabase();
		return contacts;
	}
}
